﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.PaymentEnums;
using BCEntity.TMS.AgentFlowRecord;
using BCEntity.TMS.AgentWallet;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCData.TMS.AgentFlowRecord
{
    public class AgentFlowRecordData : IAgentFlowRecordData
    {
        private readonly IDatabaseContext database;
        private readonly string QUERY = @"SELECT
		                                    AgentFlowRecordId,
		                                    AgentRecordId,
		                                    AgentName,
		                                    FlowType,
		                                    FlowTypeName,
		                                    OrderNo,
		                                    Balance,
		                                    FlowDirection,
		                                    Amount,
		                                    Channel,
		                                    Remark,
		                                    CreateTime,
		                                    RiskLevel
                                        FROM
                                            agentflowrecord ";



        #region 构造函数
        public AgentFlowRecordData(IDatabaseContext database)
        {
            this.database = database;
        }
        #endregion

        #region InsertAsync
        /// <summary>
        /// 添加新代理商流水记录纪录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<AgentFlowRecordEntity> InsertAsync(AgentFlowRecordEntity entity)
        {
            return await this.database.Master.InsertAsync(entity, database.Transaction);
        }
        #endregion

        #region updateAsync
        /// <summary>
        /// 修改代理商流水记录记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<AgentFlowRecordEntity> UpdateAsync(AgentFlowRecordEntity entity)
        {
            return await this.database.Master.UpdateAsync(entity, database.Transaction);
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除代理商流水记录记录
        /// </summary>
        /// <param name="agentflowrecordId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(long agentflowrecordId)
        {
            string sql = "DELETE FROM agentflowrecord WHERE agentflowrecordId = ?agentflowrecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?agentflowrecordId", agentflowrecordId, DbType.Int64);
            return await this.database.Master.ExecuteAsync(sql, parameters, database.Transaction) > 0;
        }
        #endregion

        #region GetById
        /// <summary>
        /// 获取代理商流水记录记录
        /// </summary>
        /// <param name="agentflowrecordId"></param>
        /// <returns></returns>
        public async Task<AgentFlowRecordEntity> GetEntityAsync(long agentflowrecordId)
        {
            string sql = QUERY + " WHERE  agentflowrecordId = ?agentflowrecordId";

            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?agentflowrecordId", agentflowrecordId, DbType.Int64);
            return await this.database.Slave.QueryEntityAsync<AgentFlowRecordEntity>(sql, parameters);
        }
        #endregion

        #region GetListAsync 查询代理商流水记录记录
        public async Task<(IEnumerable<AgentFlowRecordEntity>, int)> GetListAsync(int pageIndex, int pageSize)
        {

            DynamicParameters parameters = new DynamicParameters();
            //查询条件
            List<string> wheres = new List<string>();


            string sql = string.Format(@"{0} {1} ; SELECT COUNT(1) FROM  agentflowrecord  {1}",
                   QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize
                  );

            return await this.database.Slave.QueryPageableListAsync<AgentFlowRecordEntity>(sql, parameters);
        }
        #endregion

        public async Task<(IEnumerable<AgentFlowRecordEntity>, int)> GetPageableList(long? agentRecordId, string orderNo,
            FlowType? flowType, FlowDirectionType? flowDirection, PaymentChannelType? payChannel, DateTime? startDate, DateTime? endDate,
                    bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (agentRecordId.HasValue)
            {
                wheres.Add("AgentRecordId=?AgentRecordId");
                parameters.Add("?AgentRecordId", agentRecordId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                wheres.Add("OrderNo=?OrderNo");
                parameters.Add("?OrderNo", orderNo, DbType.AnsiString, size: 50);
            }
            if (flowType.HasValue)
            {
                wheres.Add("FlowType=?FlowType");
                parameters.Add("?FlowType", flowType.ToString(), DbType.AnsiString);
            }
            if (flowDirection.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirection.ToString(), DbType.AnsiString);
            }
            if (payChannel.HasValue)
            {
                wheres.Add("Channel=?Channel");
                parameters.Add("?Channel", payChannel.ToString(), DbType.AnsiString);
            }
            if (startDate.HasValue)
            {
                wheres.Add("CreateTime>=?StartDate");
                parameters.Add("?StartDate", startDate.Value.Date, DbType.Date);
            }
            if (endDate.HasValue)
            {
                wheres.Add("CreateTime <?EndDate");
                parameters.Add("?EndDate", endDate.Value.AddDays(1).Date, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY AgentFlowRecordId {4} LIMIT {2},{3};
                               SELECT Count(1) FROM agentflowrecord {1}",
                 QUERY,
                 wheres.Count > 0 ? string.Format(" WHERE {0}", string.Join(" AND ", wheres)) : string.Empty,
                 (pageIndex - 1) * pageSize,
                 pageSize,
                 ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            return await this.database.Slave.QueryPageableListAsync<AgentFlowRecordEntity>(sql, parameters);
        }


        public async Task<(IEnumerable<AgentFlowRecordEntity>, int)> GetAgentFlowDetails(long agentRecordId, FlowType? flowType, FlowDirectionType? flowDirectionType, decimal? minAmount,
            decimal? maxAmount, PaymentChannelType? paymentChannelType, DateTime? startDate,DateTime? endDate, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("AgentRecordId=?AgentRecordId");
            parameters.Add("?AgentRecordId", agentRecordId, DbType.Int64);
            if (flowType.HasValue)
            {
                wheres.Add("FlowType=?FlowType");
                parameters.Add("?FlowType", flowType.Value.ToString(), DbType.AnsiString);
            }
            if (flowDirectionType.HasValue)
            {
                wheres.Add("FlowDirection=?FlowDirection");
                parameters.Add("?FlowDirection", flowDirectionType.Value.ToString(), DbType.AnsiString);
            }
            if (paymentChannelType.HasValue)
            {
                wheres.Add("Channel=?Channel");
                parameters.Add("?Channel", paymentChannelType.Value.ToString(), DbType.AnsiString);
            }
            if (minAmount.HasValue)
            {
                wheres.Add("Amount>=?MinAmount");
                parameters.Add("?MinAmount", minAmount.Value, DbType.Decimal);
            }
            if (maxAmount.HasValue)
            {
                wheres.Add("Amount<=?MaxAmount");
                parameters.Add("?MaxAmount", maxAmount.Value, DbType.Decimal);
            }
            if (startDate.HasValue)
            {
                wheres.Add("CreateTime>=?StartDate");
                parameters.Add("?StartDate", startDate.Value.Date, DbType.Date);
            }
            if (endDate.HasValue)
            {
                wheres.Add("CreateTime <?EndDate");
                parameters.Add("?EndDate", endDate.Value.AddDays(1).Date, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime {4} LIMIT {2},{3};
                               SELECT Count(1) FROM agentflowrecord {1}",
                 QUERY,
                 wheres.Count > 0 ? string.Format(" WHERE {0}", string.Join(" AND ", wheres)) : string.Empty,
                 (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                 pageSize,
                 ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            return await database.Slave.QueryPageableListAsync<AgentFlowRecordEntity>(sql, parameters);
        }
    }
}

